/**
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "../../../common/data_utils.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
extern void welford_update_custom_do(uint32_t blockDim, void *l2ctrl, void *stream, uint8_t *srcGm, uint8_t *inMeanGm,
    uint8_t *inVarGm, uint8_t *outMeanGm, uint8_t *outVarGm, uint8_t *workspace, uint8_t *tiling);
#else
#include "tikicpulib.h"
extern "C" __global__ __aicore__ void welford_update_custom(GM_ADDR srcGm, GM_ADDR inMeanGm, GM_ADDR inVarGm,
    GM_ADDR outMeanGm, GM_ADDR outVarGm, GM_ADDR workspace, GM_ADDR tiling);
#endif
constexpr uint8_t BLOCK_DIM = 1;
constexpr uint32_t TILINGDATA_SIZE = 6;
constexpr uint32_t WORKSPACE_SIZE = 1024 * 1024;

constexpr bool ISINPLACE = true;
constexpr uint8_t RN_SIZE = 1;
constexpr uint32_t AB_SIZE = 64;
constexpr uint32_t AB_LENGTH = 35;
constexpr float NREC = 1.0 / 8;

extern uint8_t *GenerateTiling(bool inplace, uint32_t nLength, uint32_t rLength, uint32_t abComputeLength,
    float nRec);

static bool CompareResult(const void *outputData, int64_t outSize, std::string goldenName)
{
    void *goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t *)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void **)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile("../output/golden_" + goldenName + ".bin", goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden_%s.bin success!\n", goldenName.c_str());
    } else {
        printf("test failed!\n");
        return false;
    }
    constexpr float EPS = 1e-4;
    int64_t wrongNum = 0;

    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = (reinterpret_cast<const float *>(outputData))[i];
        float b = (reinterpret_cast<const float *>(goldenData))[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult golden_%s.bin failed output is %lf, golden is %lf\n", goldenName.c_str(), a, b);
            wrongNum++;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void *)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    if (wrongNum != 0) {
        return false;
    } else {
        printf("CompareResult golden_%s.bin success!\n", goldenName.c_str());
        return true;
    }
}

int32_t main(int32_t argc, char *argv[])
{
    uint32_t blockDim = BLOCK_DIM;
    size_t inputSrcSize = RN_SIZE * AB_SIZE * sizeof(float);
    size_t inputMeanSize = RN_SIZE * AB_SIZE * sizeof(float);
    size_t inputVarSize = RN_SIZE * AB_SIZE * sizeof(float);
    size_t outputMeanSize = RN_SIZE * AB_SIZE * sizeof(float);
    size_t outputVarSize = RN_SIZE * AB_SIZE * sizeof(float);

    size_t workspaceSize = WORKSPACE_SIZE;
    size_t tilingFileSize = TILINGDATA_SIZE * sizeof(uint32_t);
    uint8_t *tilingBuf = GenerateTiling(ISINPLACE, RN_SIZE, AB_SIZE, AB_LENGTH, NREC);

#ifdef ASCENDC_CPU_DEBUG
    uint8_t *inputSrc = (uint8_t *)AscendC::GmAlloc(inputSrcSize);
    uint8_t *inputMean = (uint8_t *)AscendC::GmAlloc(inputMeanSize);
    uint8_t *inputVar = (uint8_t *)AscendC::GmAlloc(inputVarSize);
    uint8_t *outputMean = (uint8_t *)AscendC::GmAlloc(outputMeanSize);
    uint8_t *outputVar = (uint8_t *)AscendC::GmAlloc(outputVarSize);

    uint8_t *workspace = (uint8_t *)AscendC::GmAlloc(workspaceSize);
    uint8_t *tiling = (uint8_t *)AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/input_srcGm.bin", inputSrcSize, inputSrc, inputSrcSize);
    ReadFile("../input/input_inMeanGm.bin", inputMeanSize, inputMean, inputMeanSize);
    ReadFile("../input/input_inVarGm.bin", inputVarSize, inputVar, inputVarSize);

    memcpy_s(tiling, tilingFileSize, tilingBuf, tilingFileSize);

    AscendC::SetKernelMode(KernelMode::AIV_MODE);
    ICPU_RUN_KF(welford_update_custom, blockDim, inputSrc, inputMean, inputVar, outputMean, outputVar, workspace,
        tiling);

    WriteFile("../output/output_outMeanGm.bin", outputMean, outputMeanSize);
    WriteFile("../output/output_outVarGm.bin", outputVar, outputVarSize);

    bool goldenResult = true;
    goldenResult &= CompareResult(outputMean, outputMeanSize, "outMeanGm");
    goldenResult &= CompareResult(outputVar, outputVarSize, "outVarGm");
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    AscendC::GmFree((void *)inputSrc);
    AscendC::GmFree((void *)inputMean);
    AscendC::GmFree((void *)inputVar);
    AscendC::GmFree((void *)outputMean);
    AscendC::GmFree((void *)outputVar);
    AscendC::GmFree((void *)workspace);
    AscendC::GmFree((void *)tiling);

#else
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t *srcHost, *inMeanHost, *inVarHost, *outMeanHost, *outVarHost, *workspaceHost;
    uint8_t *srcDevice, *inMeanDevice, *inVarDevice, *outMeanDevice, *outVarDevice, *workspaceDevice, *tilingDevice;

    CHECK_ACL(aclrtMallocHost((void **)(&srcHost), inputSrcSize));
    CHECK_ACL(aclrtMallocHost((void **)(&inMeanHost), inputMeanSize));
    CHECK_ACL(aclrtMallocHost((void **)(&inVarHost), inputVarSize));
    CHECK_ACL(aclrtMallocHost((void **)(&outMeanHost), outputMeanSize));
    CHECK_ACL(aclrtMallocHost((void **)(&outVarHost), outputVarSize));
    CHECK_ACL(aclrtMallocHost((void **)(&workspaceHost), workspaceSize));

    CHECK_ACL(aclrtMalloc((void **)&srcDevice, inputSrcSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&inMeanDevice, inputMeanSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&inVarDevice, inputVarSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&outMeanDevice, outputMeanSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&outVarDevice, outputVarSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&tilingDevice, tilingFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    ReadFile("../input/input_srcGm.bin", inputSrcSize, srcHost, inputSrcSize);
    ReadFile("../input/input_inMeanGm.bin", inputMeanSize, inMeanHost, inputMeanSize);
    ReadFile("../input/input_inVarGm.bin", inputVarSize, inVarHost, inputVarSize);

    CHECK_ACL(aclrtMemcpy(workspaceDevice, workspaceSize, workspaceHost, workspaceSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, tilingBuf, tilingFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    CHECK_ACL(aclrtMemcpy(srcDevice, inputMeanSize, srcHost, inputMeanSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(inMeanDevice, inputMeanSize, inMeanHost, inputMeanSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(inVarDevice, inputVarSize, inVarHost, inputVarSize, ACL_MEMCPY_HOST_TO_DEVICE));

    welford_update_custom_do(blockDim, nullptr, stream, srcDevice, inMeanDevice, inVarDevice, outMeanDevice,
        outVarDevice, workspaceDevice, tilingDevice);

    CHECK_ACL(aclrtSynchronizeStream(stream));

    CHECK_ACL(aclrtMemcpy(outMeanHost, outputMeanSize, outMeanDevice, outputMeanSize, ACL_MEMCPY_DEVICE_TO_HOST));
    CHECK_ACL(aclrtMemcpy(outVarHost, outputVarSize, outVarDevice, outputVarSize, ACL_MEMCPY_DEVICE_TO_HOST));

    WriteFile("../output/output_outMeanGm.bin", outMeanHost, outputMeanSize);
    WriteFile("../output/output_outVarGm.bin", outVarHost, outputVarSize);

    bool goldenResult = true;
    goldenResult &= CompareResult(outMeanHost, outputMeanSize, "outMeanGm");
    goldenResult &= CompareResult(outVarHost, outputVarSize, "outVarGm");
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    CHECK_ACL(aclrtFree(srcDevice));
    CHECK_ACL(aclrtFree(inMeanDevice));
    CHECK_ACL(aclrtFree(inVarDevice));
    CHECK_ACL(aclrtFree(outMeanDevice));
    CHECK_ACL(aclrtFree(outVarDevice));
    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFree(tilingDevice));

    CHECK_ACL(aclrtFreeHost(srcHost));
    CHECK_ACL(aclrtFreeHost(inMeanHost));
    CHECK_ACL(aclrtFreeHost(inVarHost));
    CHECK_ACL(aclrtFreeHost(outMeanHost));
    CHECK_ACL(aclrtFreeHost(outVarHost));
    CHECK_ACL(aclrtFreeHost(workspaceHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    free(tilingBuf);
    return 0;
}
